import { Color, Fog, PCFSoftShadowMap, SRGBColorSpace, Vector3 } from "three";
import "./weapp-adapter";
import "./WxAdapter";
import Render from "./Core/Render";
import World from "./Core/World";
import Util from "./Utils/Util";
import Hud from "./Core/Hud";

// window.canvas = document.createElement("canvas");
// canvas.style.width = '100vw'
// canvas.style.height = '100vh'
// document.body.appendChild(canvas);

declare global {
  let render: Render;
  let world: World;
  let hud: Hud;
  let canvas: HTMLCanvasElement;
  let ctx: WebGLRenderingContext;
  let WXWebAssembly: any;
  interface Window {
    render: Render;
    world: World;
    hud: Hud;
    canvas: HTMLCanvasElement;
    ctx: WebGLRenderingContext;
    WXWebAssembly: any;
  }
}

export default class Startup {
  constructor() {
    this.Init();
  }

  Init() {
    this.CreateRender();
    this.CreateWorld();
    this.CreateHud();

    this.RegisterTouchEvent();
    this.touchEvents.push(hud.RockerControl.bind(hud));
    render.animate();
  }

  CreateRender() {
    window.render = new Render(true)
      .setScene((s) => {
        s.background = new Color("black");
      })
      .setRender((r) => {
        r.shadowMap.enabled = true;
        r.shadowMap.type = PCFSoftShadowMap;
        r.outputColorSpace = SRGBColorSpace;
        r.setPixelRatio(window.devicePixelRatio);
        r.setSize(window.innerWidth, window.innerHeight);

        r.autoClear = false;
      })
      .setCamera((c) => {
        c.fov = 45;
        c.aspect = window.innerWidth / window.innerHeight;
        c.near = 0.01;
        c.far = 999;

        c.updateProjectionMatrix();
      });

    Util.ktx2Loader.detectSupport(render.r);
  }

  CreateWorld() {
    window.world = new World();
  }

  CreateHud() {
    window.hud = new Hud();
  }

  private touchEvents: Function[] = [];
  private TouchEventHubs(e: TouchEvent) {
    Util.pointer.x = (e.changedTouches[0].clientX / window.innerWidth) * 2 - 1;
    Util.pointer.y = -(e.changedTouches[0].clientY / window.innerHeight) * 2 + 1;

    // Util.raycaster.setFromCamera(Util.pointer, render.mainCamera);
    // let intersects = Util.raycaster.intersectObjects(render.mainScene.children);

    // Util.raycaster.setFromCamera(Util.pointer, render.hudCamera);
    // let hudIntersects = Util.raycaster.intersectObjects(render.hudScene.children);
    // this.touchEvents.forEach((event) => event(e, intersects, hudIntersects));
    this.touchEvents.forEach((event) => event(e));
  }

  RegisterTouchEvent() {
    let events = ["Start", "End", "Move"];
    events.forEach((e) => {
      window.addEventListener(("Touch" + e).toLowerCase(), this.TouchEventHubs.bind(this));
    });
  }
}

new Startup();
